<template>
  <div class="inspection-record-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="任务名称">
          <el-input
            v-model.trim="searchForm.taskName"
            placeholder="请输入任务名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="巡检设备">
          <el-select v-model="searchForm.deviceId" placeholder="请选择巡检设备">
            <el-option label="全部" :value="''"></el-option>
            <el-option
              v-for="device in deviceList"
              :key="device.id"
              :label="device.deviceName"
              :value="device.id"
            ></el-option>
          </el-select>
        </el-form-item>
  
        <el-form-item label="巡检结果">
          <el-select v-model="searchForm.status" placeholder="请选择巡检结果">
            <el-option label="全部" :value="''"></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="异常" :value="2"></el-option>
          </el-select>
        </el-form-item>
 
        <el-form-item>
          <el-button type="primary" @click="get_record_list">搜索</el-button>
          <el-button @click="handle_reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区 -->
    <div class="action-buttons">
      <el-button type="primary" @click="dialog_visible = true" v-has="'inspection:record:add'">新增巡检记录</el-button>
      <el-button type="danger" @click="batch_delete" v-has="'inspection:record:delete'" :disabled="multiple_selection.length === 0">批量删除</el-button>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        style="width: 100%"
        border
   
        v-loading="loading"
      >

        <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
        <el-table-column label="任务名称" width="180">
          <template slot-scope="scope">
            <span>{{ getTaskName(scope.row.taskId) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="巡检设备">
          <template slot-scope="scope">
            <span>{{ getDeviceName(scope.row.deviceId) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="巡检人员">
          <template slot-scope="scope">
            <span>{{ getUserName(scope.row.inspectorId) || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inspectionTime" label="巡检时间" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.inspectionTime}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="巡检备注" show-overflow-tooltip></el-table-column>
        <el-table-column prop="status" label="巡检结果" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '正常' : '异常' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditStatus" label="审核状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getAuditStatusTag(scope.row.auditStatus)">
              {{ getAuditStatusText(scope.row.auditStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="auditTime" label="审核时间" width="180">
          <template slot-scope="scope">
            <span>{{ scope.row.auditTime}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditRemarks" label="审核备注" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handle_detail(scope.row.id)">详情</el-button>
            <el-button size="mini" type="primary" @click="handle_edit(scope.row.id)" >编辑</el-button>
            <el-button size="mini" type="danger" @click="handle_delete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next, jumper, total"
          :total="total"
          :page-size="page_size"
          :current-page="page_index"
          @current-change="handle_current_change"
          @size-change="handle_size_change"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialog_title"
      :visible.sync="dialog_visible"
      width="600px"
      destroy-on-close
    >
      <el-form
        :model="edit_form"
        ref="edit_form"
        label-width="120px"
        :rules="rules"
      >
        <el-form-item label="任务名称" prop="taskId">
          <el-select v-model="edit_form.taskId" placeholder="请选择任务名称">
            <el-option
              v-for="task in taskList"
              :key="task.id"
              :label="task.task_name"
              :value="task.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检设备" prop="deviceId">
          <el-select v-model="edit_form.deviceId" placeholder="请选择巡检设备">
            <el-option
              v-for="device in deviceList"
              :key="device.id"
              :label="device.device_name"
              :value="device.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检人员" prop="inspectorId">
          <el-select v-model="edit_form.inspectorId" placeholder="请选择巡检人员">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.username"
              :value="user.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="巡检时间" prop="inspectionTime">
          <el-date-picker
            v-model="edit_form.inspectionTime"
            type="datetime"
            placeholder="选择巡检时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="巡检结果" prop="status">
          <el-radio-group v-model="edit_form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">异常</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="巡检备注" prop="remarks">
          <el-input
            v-model="edit_form.remarks"
            type="textarea"
            placeholder="请输入巡检备注"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog_visible = false">取消</el-button>
        <el-button type="primary" @click="handle_submit">确定</el-button>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      title="巡检记录详情"
      :visible.sync="detail_visible"
      width="800px"
      destroy-on-close
    >
      <el-form label-width="120px" :model="detail_form" class="detail-form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="记录ID">
              <el-input v-model="detail_form.id" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="任务名称">
              <el-input v-model="detail_form.taskName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡检设备">
              <el-input v-model="detail_form.deviceName" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检人员">
              <el-input v-model="detail_form.inspectorName" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="巡检时间">
              <el-input :value="detail_form.inspectionTime" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡检结果">
              <el-input :value="detail_form.status === 1 ? '正常' : '异常'" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="巡检备注">
              <el-input v-model="detail_form.remarks" type="textarea" :rows="3" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核状态">
              <el-input :value="getAuditStatusText(detail_form.auditStatus)" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核时间">
              <el-input :value="detail_form.auditTime " disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="审核人">
              <el-input v-model="detail_form.auditUserName || '-'" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核备注">
              <el-input v-model="detail_form.auditRemarks || '-'" type="textarea" :rows="3" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detail_visible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import inspectionRecordApi from '@/api/inspection-record';
import userApi from '@/api/sys-user';
import taskApi from '@/api/inspection-task';
import deviceApi from '@/api/device';



export default {
  name: 'InspectionRecord',
  data() {
    return {
      // 搜索表单
      searchForm: {
        taskName: '',
        deviceId: '',
        inspectorId: '',
        status: '',
        auditStatus: ''
      },
      // 表格数据
      tableData: [],
      // 任务列表
      taskList: [],
      // 设备列表
      deviceList: [],
      // 用户列表
      userList: [],
      // 分页
      page_index: 1,
      page_size: 10,
      total: 0,
      // 对话框
      dialog_visible: false,
      dialog_title: '新增巡检记录',
      // 编辑表单
      edit_form: {
        id: '',
        taskId: '',
        deviceId: '',
        inspectorId: '',
        inspectionTime: new Date(),
        status: 1,
        remarks: ''
      },
      // 详情表单
      detail_form: {},
      detail_visible: false,
      // 加载状态
      loading: false,
      // 多选
      multiple_selection: [],
      // 表单验证规则
      rules: {
        taskId: [{ required: true, message: '请选择任务名称', trigger: 'change' }],
        deviceId: [{ required: true, message: '请选择巡检设备', trigger: 'change' }],
        inspectorId: [{ required: true, message: '请选择巡检人员', trigger: 'change' }],
        inspectionTime: [{ required: true, message: '请选择巡检时间', trigger: 'change' }],
        status: [{ required: true, message: '请选择巡检结果', trigger: 'change' }]
      }
    };
  },
  created() {
   
    this.get_record_list();
    this.load_select_data(); 
  },
  methods: {

    
    // 获取任务名称
    getTaskName(taskId) {
      if (!taskId) return '';
      const task = this.taskList.find(item => item && item.id === taskId);
      return task ? task.taskName : '';
    },
    
    // 获取设备名称
    getDeviceName(deviceId) {
      if (!deviceId) return '';
      const device = this.deviceList.find(item => item && item.id === deviceId);
      return device ? device.deviceName : '';
    },
    
    // 获取用户名称
    getUserName(userId) {
      if (!userId) return '';
      const user = this.userList.find(item => item && item.id === userId);
      return user ? user.username : '';
    },
    
    // 获取审核状态标签类型
    getAuditStatusTag(status) {
      if (status === undefined || status === null) return 'default';
      const tagMap = {
        0: 'warning',
        1: 'info',
        2: 'success',
        3: 'danger'
      };
      return tagMap[status] || 'default';
    },
    
    // 获取审核状态文本
    getAuditStatusText(status) {
      if (status === undefined || status === null) return '未知';
      const textMap = {
        0: '待审核',
        1: '审核中',
        2: '审核通过',
        3: '审核拒绝'
      };
      return textMap[status] || '未知';
    },
    
    // 加载下拉框数据
    load_select_data() {
      // 加载任务列表
      taskApi.list().then(res => {
        this.taskList = res.data.records || [];
      }).catch(error => {
        console.error('加载任务列表失败:', error);
      });
      
      // 加载设备列表
      deviceApi.list().then(res => {
        this.deviceList = res.data.records || [];
      }).catch(error => {
        console.error('加载设备列表失败:', error);
      });
      
      // 加载用户列表
      userApi.list().then(res => {
        this.userList = res.data.records || [];
      }).catch(error => {
        console.error('加载用户列表失败:', error);
      });
    },
    
    // 获取巡检记录列表
    get_record_list() {
      this.loading = true;
      
      const params = {
        page_index: this.page_index,
        page_size: this.page_size,
        ...this.searchForm
      };
      
      inspectionRecordApi.list(params)
        .then((res) => {
          // 确保数据项的完整性，避免访问null属性
          this.tableData = (res.data?.records || []).map(item => item || {});
          this.total = res.data?.total || 0;
        })
        .catch((error) => {
          this.$message.error('获取巡检记录列表失败：' + (error.message || '未知错误'));
          console.error('获取巡检记录列表失败:', error);
        })
        .finally(() => {
          this.loading = false;
        });
    },
    
    // 重置表单
    handle_reset() {
      this.searchForm = {
        taskName: '',
        deviceId: '',
        inspectorId: '',
        status: '',
        auditStatus: ''
      };
      this.get_record_list();
    },
    
    // 分页处理
    handle_current_change(val) {
      this.page_index = val;
      this.get_record_list();
    },
    
    handle_size_change(val) {
      this.page_size = val;
      this.page_index = 1;
      this.get_record_list();
    },
    
 
    // 打开编辑对话框
    handle_edit(id) {
      this.dialog_title = '编辑巡检记录';
      this.dialog_visible = true;
      
      inspectionRecordApi.detail(id).then(res => {
        const data = res.data || {};
        this.edit_form = {
          id: data.id,
          taskId: data.taskId,
          deviceId: data.deviceId,
          inspectorId: data.inspectorId,
          inspectionTime: data.inspectionTime ? new Date(data.inspectionTime) : new Date(),
          status: data.status || 1,
          remarks: data.remarks || ''
        };
      }).catch(error => {
        this.$message.error('获取巡检记录详情失败：' + (error.message || '未知错误'));
        console.error('获取巡检记录详情失败:', error);
        this.dialog_visible = false;
      });
    },
    
    // 查看详情
    handle_detail(id) {
      inspectionRecordApi.detail(id)
        .then((res) => {
          const data = res.data || {};
          this.detail_form = {
            id: data.id,
            taskName: this.getTaskName(data.taskId),
            deviceName: this.getDeviceName(data.deviceId),
            inspectorName: this.getUserName(data.inspectorId),
            inspectionTime: data.inspectionTime,
            status: data.status,
            remarks: data.remarks,
            auditStatus: data.auditStatus,
            auditTime: data.auditTime,
            auditUserId: data.auditUserId,
            auditUserName: this.getUserName(data.auditUserId),
            auditRemarks: data.auditRemarks
          };
          this.detail_visible = true;
        })
        .catch((error) => {
          this.$message.error('获取巡检记录详情失败：' + (error.message || '未知错误'));
          console.error('获取巡检记录详情失败:', error);
        });
    },
    
    // 删除
    handle_delete(id) {
      this.$confirm('确定要删除这条巡检记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        inspectionRecordApi.delete(id)
          .then((res) => {
            this.$message.success('删除成功');
            this.get_record_list();
          })
          .catch((error) => {
            this.$message.error('删除失败：' + (error.message || '未知错误'));
            console.error('删除巡检记录失败:', error);
          });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 批量删除
    batch_delete() {
      if (this.multiple_selection.length === 0) {
        this.$message.warning('请先选择要删除的记录');
        return;
      }
      
      this.$confirm(`确定要删除选中的 ${this.multiple_selection.length} 条巡检记录吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.multiple_selection.map(row => row.id);
        Promise.all(ids.map(id => inspectionRecordApi.delete(id)))
          .then(() => {
            this.$message.success('批量删除成功');
            this.get_record_list();
            this.multiple_selection = [];
          })
          .catch((error) => {
            this.$message.error('批量删除失败：' + (error.message || '未知错误'));
            console.error('批量删除巡检记录失败:', error);
          });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 提交表单
    handle_submit() {
      this.$refs.edit_form.validate((valid) => {
        if (valid) {
          const form_data = {
            ...this.edit_form
          };
          
          const apiMethod = this.edit_form.id ? inspectionRecordApi.update : inspectionRecordApi.add;
      
      apiMethod(form_data)
            .then((res) => {
              this.$message.success(this.edit_form.id ? '编辑成功' : '新增成功');
              this.dialog_visible = false;
              this.get_record_list();
              this.reset_edit_form();
            })
            .catch((error) => {
              this.$message.error((this.edit_form.id ? '编辑' : '新增') + '失败：' + (error.message || '未知错误'));
              console.error((this.edit_form.id ? '编辑' : '新增') + '巡检记录失败:', error);
            });
        }
      });
    },
    
    // 重置编辑表单
    reset_edit_form() {
      this.edit_form = {
        id: '',
        taskId: '',
        deviceId: '',
        inspectorId: '',
        inspectionTime: new Date(),
        status: 1,
        remarks: ''
      };
      
      if (this.$refs.edit_form) {
        this.$refs.edit_form.resetFields();
      }
    }
  }
};
</script>

<style scoped>
.inspection-record-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin-bottom: 0;
}

.action-buttons {
  margin-bottom: 20px;
}

.action-buttons .el-button {
  margin-right: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.detail-form .el-form-item {
  margin-bottom: 15px;
}

.el-table .cell {
  white-space: normal;
  word-break: break-word;
}

.dialog-footer {
  text-align: right;
}
</style>